<template>
  <div class="viewport-dropdown">
    <popover
      v-model="visible"
      popper-class="viewport-dropdown__popper"
      trigger="click"
    >
      <div
        class="viewport-dropdown__button"
        slot="reference"
        style="white-space: nowrap"
      >
        <span>{{
          (activeViewport && activeViewport.viewName) || $t('component.viewportDropdown.defaultName')
        }}</span>
        <i class="iconfont icon-down-fill"></i>
      </div>
      <div class="viewport-dropdown__content">
        <div class="viewport-dropdown__title">
          <span>{{$t('component.viewportDropdown.title')}}</span>
          <tooltip :content="viewportTooltip" placement="right">
            <!-- <div class="" slot="content">
              由快捷筛选和高级筛选及选择列组合保存为视图，方便快捷查看
            </div> -->
            <i class="iconfont icon-jieshishuoming"></i>
          </tooltip>
        </div>
        <div class="viewport-dropdown__scroll-wrap">
          <div class="viewport-dropdown__list">
            <div
              class="viewport-dropdown__list-item"
              :class="{ active: activeViewport.viewId === item.viewId }"
              v-for="(item, index) of list"
              :key="item.viewId"
              @click="handleChoose(item)"
            >
              <div class="viewport-dropdown__list-item-name">
                {{ item.viewName }}
              </div>
              <div
                class="viewport-dropdown__list-item-type"
                v-show="item.viewId && !item.authEdit && !item.isPre"
              >
                <span class="tag">
                  {{$t('component.viewportDropdown.public')}}
                  <!-- {{ item.authEdit ? '个人' : '公开' }} -->
                </span>
              </div>
              <dropdown
                v-if="item.authEdit"
                trigger="click"
                placement="right"
                @command="changeCommand(item, index, $event)"
              >
                <span class="operator-drop-down" @click.stop>
                  <i class="iconfont icon-MoreOutlined"></i>
                </span>
                <dropdown-menu slot="dropdown">
                  <dropdown-item command="edit">{{$t('common.base.edit')}}</dropdown-item>
                  <dropdown-item command="delete">{{$t('common.base.delete')}}</dropdown-item>
                </dropdown-menu>
              </dropdown>
              <!-- <div
                class="viewport-dropdown__list-item-operator"
                v-if="item.authEdit"
              >
                <span @click.stop="handleEdit(item)">
                  <i class="iconfont icon-bianji1"></i>
                </span>
                <span @click.stop="handleRemove(item, index)">
                  <i class="iconfont icon-shanchu-copy"></i>
                </span>
              </div> -->
            </div>
          </div>
        </div>
        <div class="viewport-dropdown__create-btn" @click.stop="handleCreate">
          <i class="iconfont icon-add"></i>
          <span>{{$t('component.advancedSearch.modal.createTitle')}}</span>
        </div>
      </div>
    </popover>
  </div>
</template>
<script>
import { defineComponent, ref, watch } from 'vue';
import Vue from 'vue';
import { useViewport } from './viewport';
import { toast, confirm } from '@src/util/platform';
import { delViewport } from '@src/api/Viewport';
import { Popover, Dropdown, DropdownItem, DropdownMenu, Tooltip } from 'element-ui'
import i18n from '@src/locales';

const viewportTooltip = i18n.t('component.viewportDropdown.tooltip');

export default defineComponent({
  name: 'ViewportDropdown',
  components: {
    Popover, 
    Dropdown, 
    DropdownItem, 
    DropdownMenu, 
    Tooltip,
  },
  props: {
    module: {
      type: String,
      default: '', // TODO 常量
    },
    currentView: {
      type: Object,
      default: () => null,
    },
    preViews: {
      type: Array,
      default: () => [],
    },
  },
  setup(props, { emit }) {
    const Track = Vue.prototype.$track;
    
    const visible = ref(false);
    const { list, getList, activeViewport, chooseViewport, removeViewport } =
      useViewport(props.module, props.preViews);

    /**
     * 隐藏菜单
     */
    function hideMenu() {
      visible.value = false;
    }

    // 选择视图
    function handleChoose(_v) {
      Track.clickStat(Track.formatParams('CHOOSE_SEARCH_VIEW'));

      chooseViewport(_v);
      emit('choose', _v);
      emit('update:currentView', _v);
      hideMenu();
    }

    // 点击新建
    function handleCreate() {
      Track.clickStat(Track.formatParams('CREATE_SEARCH_VIEW'));
      hideMenu();
      emit('create');
    }

    // 点击编辑
    function handleEdit(_v) {
      hideMenu();
      emit('edit', _v);
    }

    // 删除视图
    async function handleRemove(item, index) {
      hideMenu();
      if (
        !(await confirm(i18n.t('component.viewportDropdown.deleteTip', {viewName: item.viewName}), '', {
          type: 'warning',
          customClass: 'delete-view-confirm',
          showClose: false,
        }))
      ) {
        return;
      }
      try {
        const params = {
          viewId: item.viewId,
          module: props.module,
        };
        await delViewport(params);
        hideMenu();
        toast(i18n.t('common.base.deleteSuccess'));
        const isChange = removeViewport(index);
        isChange && handleChoose(activeViewport.value);
        refresh();
      } catch (error) {
        toast(i18n.t('common.base.deleteFail'), 'error');
      }
    }

    /**
     * 刷新
     * @param {string} [视图ID] 有id选中此视图
     */
    function refresh(id) {
      getList().then(list => {
        if (id) {
          const _v = (list || []).find(item => id === item.viewId);
          _v && handleChoose(_v);
        }
      });
    }

    // 操作视图项
    function changeCommand(item, index, command) {
      const fn = {
        edit: handleEdit,
        delete: handleRemove,
      };

      fn[command](item, index);
    }

    {
      // 页面初始
      refresh();

      // 监听传入的选中视图
      watch(
        () => props.currentView,
        newValue => {
          if (!newValue) {
            chooseViewport();
          } else if (newValue.viewId !== activeViewport.value.viewId) {
            // 改变
            chooseViewport(newValue);
          }
        }
      );
    }

    return {
      visible,
      list,
      activeViewport,
      viewportTooltip,

      handleCreate,
      handleEdit,
      handleChoose,
      handleRemove,
      refresh,
      changeCommand,
    };
  },
});
</script>
<style lang="scss">
.viewport-dropdown {
  .viewport-dropdown__button {
    cursor: pointer;
    user-select: none;
    &:hover {
      color: $color-primary;
    }
  }
}
.delete-view-confirm {
  width: 424px !important;
  padding: 24px 30px;
  height: 135px;
  border-radius: 8px;
  .el-message-box__header {
    display: none;
    padding: 0;
  }
  .el-message-box__content {
    padding: 0;
    .el-message-box__message {
      color: $text-color-primary;
      font-size: 16px;
    }
  }
  .el-message-box__btns {
    margin-top: 24px;
  }
}
.viewport-dropdown__popper {
  padding: 0;
  width: 240px;
  .viewport-dropdown__content {
    .viewport-dropdown__title {
      padding: 12px;
      display: flex;
      align-items: center;
      color: $text-color-primary;
      i {
        margin-left: 4px;
        font-size: 12px;
      }
    }
    .viewport-dropdown__scroll-wrap {
      max-height: 200px;
      overflow: auto;
      .viewport-dropdown__list {
        .viewport-dropdown__list-item {
          padding: 0 12px;
          min-height: 32px;
          display: flex;
          align-items: center;
          justify-content: space-between;

          &:not(:hover) {
            .operator-drop-down {
              display: none;
            }
          }
          &:hover {
            cursor: pointer;
            background: $select-draggable-color;
            .viewport-dropdown__list-item-name {
              color: $color-primary;
            }
          }

          &.active {
            cursor: pointer;
            background: $select-draggable-color;
            .viewport-dropdown__list-item-name {
              color: $color-primary;
            }
          }
          .viewport-dropdown__list-item-name {
            padding-right: 4px;
            flex: 1;
            max-width: 9em;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .viewport-dropdown__list-item-type {
            .tag {
              padding: 4px;
              background: #f2f2f2;
              border-radius: 12px;
              font-size: 12px;
            }
          }
        }
      }
    }
    .viewport-dropdown__create-btn {
      padding: 8px 12px;
      color: $color-primary;
      border-top: 1px solid $border-color-base;
      cursor: pointer;
    }
  }
}
</style>
